package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ReidsConstants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.JiajiaWorkerVo;
import com.ruoyi.system.domain.vo.TransferBillsVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 社工Service业务层处理
 *
 * @author ruoyi
 * @date 2021-10-13
 */
@Service
public class JiajiaWorkerServiceImpl implements IJiajiaWorkerService
{

    private static final Logger logger = LoggerFactory.getLogger(JiajiaWorkerServiceImpl.class);

    @Resource
    private JiajiaWorkerMapper jiajiaWorkerMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IJiajiaTransferAccountsService jiajiaTransferAccountsService;

    @Resource
    private JiajiaPointsFlowMapper jiajiaPointsFlowMapper;
    @Autowired
    private IJiajiaMessageService messageService;

    @Autowired
    private IJiajiaWorkerMoneyChangeService workerMoneyChangeService;


    @Resource
    private JiajiaWorkerRenzhengMapper workerRenzhengMapper;

    @Resource
    private IJiajiaUserService userService;



    @Autowired
    private ApiPayService apiPayService;

    @Autowired
    private IJiajiaOrderService orderService;
    @Resource
    private JiajiaPointsFlowDetailMapper jiajiaPointsFlowDetailMapper;
    /**
     * 查询社工
     *
     * @param id 社工主键
     * @return 社工
     */
    @Override
    public JiajiaWorker selectJiajiaWorkerById(Long id) {
        return jiajiaWorkerMapper.selectJiajiaWorkerById(id);
    }

    /**
     * 查询社工列表
     *
     * @param jiajiaWorker 社工
     * @return 社工
     */
    @Override
    @DataScope(deptAlias="d")
    public List<JiajiaWorker> selectJiajiaWorkerList(JiajiaWorker jiajiaWorker) {
        jiajiaWorker.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        return jiajiaWorkerMapper.selectJiajiaWorkerList(jiajiaWorker);
    }

    /**
     * 查询社工列表
     *
     * @param jiajiaWorker 社工
     * @return 社工
     */
    @Override
    public List<JiajiaWorker> selectWorkerList(JiajiaWorker jiajiaWorker) {
        return jiajiaWorkerMapper.selectJiajiaWorkerList(jiajiaWorker);
    }

    /**
     * 新增社工
     *
     * @param jiajiaWorker 社工
     * @return 结果
     */
    @Override
    public int insertJiajiaWorker(JiajiaWorker jiajiaWorker) {
        JiajiaWorker worker=jiajiaWorkerMapper.selectRepeat(jiajiaWorker.getName(),ShiroUtils.getSysUser().getLoginName());
        if (!Optional.ofNullable(worker).isPresent()){
            return -1;
        }
        jiajiaWorker.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        jiajiaWorker.setRegion(ShiroUtils.getSysUser().getRegion());
        jiajiaWorker.setCodeAuth(1);
        int i = jiajiaWorkerMapper.insertJiajiaWorker(jiajiaWorker);
        jiajiaWorker.setAddtime(null);
        List<JiajiaWorker> jiajiaWorkers = jiajiaWorkerMapper.selectJiajiaWorkerList(jiajiaWorker);
        JiajiaWorkerRenzheng jiajiaWorkerRenzheng = new JiajiaWorkerRenzheng();
        jiajiaWorkerRenzheng.setWid(jiajiaWorkers.get(0).getId());
        jiajiaWorkerRenzheng.setCode(jiajiaWorker.getCode());
        jiajiaWorkerRenzheng.setName(jiajiaWorker.getName());
        jiajiaWorkerRenzheng.setCodeAPhoto(jiajiaWorker.getCodeAPhoto());
        jiajiaWorkerRenzheng.setCodeBPhoto(jiajiaWorker.getCodeBPhoto());
        jiajiaWorkerRenzheng.setAuthStatus(1);
        workerRenzhengMapper.insertJiajiaWorkerRenzheng(jiajiaWorkerRenzheng);
        return i;
    }

    /**
     * 修改社工
     *
     * @param jiajiaWorker 社工
     * @return 结果
     */
    @Override
    public int updateJiajiaWorker(JiajiaWorker jiajiaWorker)
    {
        return jiajiaWorkerMapper.updateJiajiaWorker(jiajiaWorker);
    }

    /**
     * 批量删除社工
     *
     * @param ids 需要删除的社工主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaWorkerByIds(String ids)
    {
        return jiajiaWorkerMapper.deleteJiajiaWorkerByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除社工信息
     *
     * @param id 社工主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaWorkerById(Long id)
    {
        return jiajiaWorkerMapper.deleteJiajiaWorkerById(id);
    }

    @Override
    public JiajiaWorker selectJiajiaWorkerByIds(Long uid) {
        return jiajiaWorkerMapper.selectJiajiaWorkerByIds(uid);
    }

    @Override
    public int insert(JiajiaWorker jiajiaWorker) {
        int i =jiajiaWorkerMapper.insert(jiajiaWorker);
        return i;
    }

    @Override
    public AjaxResult inviteJiShiList() {
        JiajiaUser jiajiaUser = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (ObjectUtil.isNull(jiajiaUser)){
            return AjaxResult.error("请刷新重试");
        }
        List<JiajiaWorker> list=jiajiaWorkerMapper.inviteJiShiList(jiajiaUser.getPhone());
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult inviteWorkerList() {
        JiajiaWorker worker = jiajiaWorkerMapper.selectJiajiaWorkerById(TokenUtil.getUid());
        if (ObjectUtil.isNull(worker)){
            return AjaxResult.error("请刷新重试");
        }
        List<JiajiaWorker> list=jiajiaWorkerMapper.inviteWorkerList(worker.getPhone());
        JiajiaWorkerVo vo=new JiajiaWorkerVo();
        vo.setList(list);
        vo.setPeopleNum(Long.valueOf(list.size()));
        return AjaxResult.success(vo);
    }

    @Override
    public void apiOrderStatus(JiajiaOrder jiajiaOrder, Integer status) {
        //社工

        JiajiaWorker worker = jiajiaWorkerMapper.selectJiajiaWorkerById(jiajiaOrder.getWid());

        //社工增加余额
        JiajiaWorkerMoneyChange moneyChange = new JiajiaWorkerMoneyChange();

        //分成比例
        String dictValue = DictUtils.getDictValue(ReidsConstants.DISTRIBUTION_RATIO, ReidsConstants.SOCIAL_WORKER);
        //项目费用
        BigDecimal subtract = jiajiaOrder.getTotalPrice().subtract(jiajiaOrder.getChuXingPrice());
        //社工结算金额
        BigDecimal bigDecimal = subtract.multiply(new BigDecimal(dictValue)).setScale(2, RoundingMode.DOWN);
        moneyChange.setChangemoney(bigDecimal);

        //结束服务
        jiajiaOrder.setEndtime(new Date());
        moneyChange.setChangeBefor(worker.getMoney());

        worker.setNum(worker.getNum().intValue()+1);
        worker.setMoney(cn.hutool.core.convert.Convert.toBigDecimal(worker.getMoney(), BigDecimal.ZERO).add(bigDecimal).add(jiajiaOrder.getChuXingPrice()));
        jiajiaWorkerMapper.updateJiajiaWorker(worker);

        moneyChange.setWid(worker.getId());
        moneyChange.setIid(jiajiaOrder.getIid());
        moneyChange.setOid(jiajiaOrder.getId());
        moneyChange.setChangeAfter(worker.getMoney());
        moneyChange.setType("订单结算");
        moneyChange.setDes("结算项目Id:"+jiajiaOrder.getIid()+",结算金额:"+bigDecimal+"元");
        workerMoneyChangeService.insertJiajiaWorkerMoneyChange(moneyChange);

        JiajiaMessage message = new JiajiaMessage();
        message.setType(1);
        message.setUid(worker.getId());
        message.setTitle("订单结算");
        message.setContent(moneyChange.getDes());
        messageService.insertJiajiaMessage(message);

        //用户点完成 准备收益数据
        List<TransferBillsVo> transferBillsVos = distributionRatio(jiajiaOrder).stream().filter(a ->Optional.ofNullable(a.getOpenid()).isPresent() && a.getOpenid().length()>0).collect(Collectors.toList());
        logger.info("transferBillsVos"+transferBillsVos.size());
        //收益数据就位
        transferBillsVos.stream().forEach(transferBillsVo ->{
            //收益人增加余额
            Long userId = transferBillsVo.getUserId();
            JiajiaUser jiajiaUser = userService.selectJiajiaUserById(userId);
            logger.info("收益人"+userId);
            BigDecimal money = jiajiaUser.getMoney()==null ? BigDecimal.ZERO:jiajiaUser.getMoney();
            BigDecimal incomeAfter = money.add(new BigDecimal(transferBillsVo.getTransferAmount()));
            jiajiaUser.setMoney(incomeAfter);
            userService.updateJiajiaUser(jiajiaUser);
            //加入流水表
            JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
            jiajiaTransferAccounts.setUserId(jiajiaUser.getId());
            jiajiaTransferAccounts.setTransferAmount(new BigDecimal(transferBillsVo.getTransferAmount()));
            jiajiaTransferAccounts.setOrderId(jiajiaOrder.getId());
            jiajiaTransferAccounts.setSourceUserId(jiajiaUser.getId());
            jiajiaTransferAccounts.setOrderType("2");
            jiajiaTransferAccounts.setTransferType(transferBillsVo.getTransferType());
            jiajiaTransferAccounts.setRemark("服务订单号"+jiajiaOrder.getOrderSn()+"产生收益");
            jiajiaTransferAccounts.setVersion(LocalDateTime.now()+String.valueOf(Math.random()));
            jiajiaTransferAccounts.setDeleted("1");
            jiajiaTransferAccountsService.insertJiajiaTransferAccounts(jiajiaTransferAccounts);
        });



        //项目金额
        BigDecimal subtract1 = jiajiaOrder.getTotalPrice().subtract(jiajiaOrder.getChuXingPrice());

        //项目总积分
        Object ratio = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.SYS_MALL_POINTS_RATION);
        BigDecimal bigDecimal1 = subtract1.multiply(new BigDecimal(ratio.toString())).setScale(0, RoundingMode.DOWN);
       logger.info("项目总积分:"+bigDecimal1);
        //项目排队积分占比
        Object ratio1 = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_queuing_to_project_ratio);
        BigDecimal bigDecimal2 = bigDecimal1.multiply(new BigDecimal(ratio1.toString())).setScale(0, RoundingMode.DOWN);
        logger.info("项目排队积分:"+bigDecimal2);

        //项目利润积分
        BigDecimal subtract2 = bigDecimal1.subtract(bigDecimal2);
        logger.info("项目利润积分:"+subtract2);

        //分账完成后积分进入商城
        JiajiaPointsFlow jiajiaPointsFlow=new JiajiaPointsFlow();
        jiajiaPointsFlow.setIid(jiajiaOrder.getIid());
        jiajiaPointsFlow.setJiajiaOrderId(jiajiaOrder.getId());
        jiajiaPointsFlow.setUid(jiajiaOrder.getUid());
        jiajiaPointsFlow.setProductTotalPrice(subtract1);
        jiajiaPointsFlow.setProductPoints(subtract2);
        jiajiaPointsFlow.setNotes("项目id："+jiajiaOrder.getIid()+"，服务类订单id:"+jiajiaOrder.getId()+"已完成利润积分进入商城");
        jiajiaPointsFlow.setIntegralStatus("0");
        jiajiaPointsFlow.setPointsType("1");
        jiajiaPointsFlowMapper.insertJiajiaPointsFlow(jiajiaPointsFlow);


        JiajiaPointsFlow jiajiaPointsFlow1=new JiajiaPointsFlow();
        BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlow1);
        jiajiaPointsFlow1.setId(null);
        jiajiaPointsFlow1.setPointsType("2");
        jiajiaPointsFlow1.setNotes("项目id："+jiajiaOrder.getIid()+"，服务类订单id:"+jiajiaOrder.getId()+"已完成排队积分进入商城");
        jiajiaPointsFlow1.setProductPoints(bigDecimal2);
        jiajiaPointsFlowMapper.insertJiajiaPointsFlow(jiajiaPointsFlow1);

        //利润积分直接解锁
        JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
        BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
        jiajiaPointsFlowDetailMapper.insertJiajiaPointsFlowDetail(jiajiaPointsFlowDetail);
        jiajiaOrder.setStatus(9);
        orderService.updateJiajiaOrder(jiajiaOrder);

    }

    @Override
    public JiajiaWorker selectJiajiaWorker(Long uid) {
        return jiajiaWorkerMapper.selectJiajiaWorker(uid);
    }


    /**
     * 分账
     */
    public List<TransferBillsVo> distributionRatio(JiajiaOrder order ){
        List<TransferBillsVo> list=new ArrayList<>();
        //分账总金额 order单位元转换微信
        BigDecimal realPrice = order.getTotalPrice().subtract(order.getChuXingPrice()).multiply(new BigDecimal("100"));

        //用户信息
        JiajiaUser user = userService.selectJiajiaUserById(order.getUid());
        logger.info("用户信息"+user.getId());
        //社工信息
        JiajiaWorker jiajiaWorker = jiajiaWorkerMapper.selectJiajiaWorkerById(order.getWid());
        JiajiaUser worker = userService.selectjiajiaUser(jiajiaWorker.getPhone());
        logger.info("社工信息"+worker.getId());

        //区县代理用户id
        Long districtAgentsUserId = null;
        //小区代理用户id
        Long communityAgentsUserId= null;

        Long deptId = order.getDeptId();
        if(Optional.ofNullable(deptId).isPresent()){
            //用户归属区域
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if(sysDept.getDistrict().equals("5")){
                SysDept sysDept1 = sysDeptService.selectDeptById(sysDept.getParentId());
                districtAgentsUserId=sysDept1.getUserId();
                communityAgentsUserId=sysDept.getUserId();
            }else if(sysDept.getDistrict().equals("3")){
                districtAgentsUserId=sysDept.getUserId();

            }else{
                throw new ServiceException("非法省代理");
            }
            //区域数据就位
            List<SysDictData> distributionRatio = DictUtils.getDictCache(ReidsConstants.DISTRIBUTION_RATIO);

            for (SysDictData sysDictData : distributionRatio) {
                TransferBillsVo transferBillsVo=new TransferBillsVo();
                if (StringUtils.equals(ReidsConstants.DISTRICT_AGENTS, sysDictData.getDictLabel())) {
                    //区域代理
                    countAgentIncome(transferBillsVo, realPrice, districtAgentsUserId, sysDictData,"1");
                    transferBillsVo.setSourceUserId(user.getId());
                    logger.info("区域代理");

                } else if (StringUtils.equals(ReidsConstants.DISTRICT_AGENTS_PROMOTERS, sysDictData.getDictLabel())) {
                    //区域代理推广员
                    if (Optional.ofNullable(districtAgentsUserId).isPresent()) {
                        JiajiaUser jiajiaUser = userService.selectJiajiaUserById(districtAgentsUserId);
                        JiajiaUser jiajiaUser1 = selectBeneficiary(jiajiaUser);
                        countPromoterIncome(transferBillsVo, realPrice, sysDictData, jiajiaUser1,"7");
                        transferBillsVo.setSourceUserId(districtAgentsUserId);
                        logger.info("区域代理推广员");

                    }
                } else if (StringUtils.equals(ReidsConstants.COMMUNITY_AGENTS, sysDictData.getDictLabel())) {
                    //小区代理
                    countAgentIncome(transferBillsVo, realPrice, communityAgentsUserId, sysDictData,"2");
                    transferBillsVo.setSourceUserId(user.getId());
                    logger.info("小区代理");

                } else if (StringUtils.equals(ReidsConstants.DISTRICT_AGENTS_PROMOTERS, sysDictData.getDictLabel())) {
                    //小区代理推广员
                    if (Optional.ofNullable(communityAgentsUserId).isPresent()) {
                        JiajiaUser jiajiaUser = userService.selectJiajiaUserById(communityAgentsUserId);
                        JiajiaUser jiajiaUser1 = selectBeneficiary(jiajiaUser);
                        countPromoterIncome(transferBillsVo, realPrice, sysDictData, jiajiaUser1,"3");
                        transferBillsVo.setSourceUserId(districtAgentsUserId);
                        logger.info("小区代理推广员");
                    }
                } else if (StringUtils.equals(ReidsConstants.SOCIAL_WORK_PROMOTER, sysDictData.getDictLabel())) {
                    //社工推广员
                    JiajiaUser jiajiaUser = userService.selectjiajiaUser(worker.getInviter());
                    logger.info("社工推广员"+jiajiaUser.getId());

                    countPromoterIncome(transferBillsVo, realPrice, sysDictData, jiajiaUser,"6");
                    transferBillsVo.setSourceUserId(worker.getId());

                } else if (StringUtils.equals(ReidsConstants.CUSTOMER_PROMOTER, sysDictData.getDictLabel())) {
                    //用户推广员 没得推广员收入归公司
                    JiajiaUser jiajiaUser = userService.selectjiajiaUser(user.getInviter());
                    logger.info("用户推广员"+jiajiaUser.getId());

                    countPromoterIncome(transferBillsVo, realPrice, sysDictData, jiajiaUser,"5");
                    transferBillsVo.setSourceUserId(user.getId());

                }

                list.add(transferBillsVo) ;
            }



        }else{
            throw new ServiceException("非法数据");
        }


        return list;
    }

    public JiajiaUser selectBeneficiary(JiajiaUser jiajiaUser ){
        boolean flag=true;
        while(flag){
            String inviter = jiajiaUser.getInviter();
            if(Optional.ofNullable(inviter).isPresent()){
                JiajiaUser jiajiaUser1 = userService.selectjiajiaUser(inviter);
                if(apiPayService.isOrdinary(jiajiaUser1)) {
                 return jiajiaUser1;
                }

            }else{
                //推荐人为空 链路断裂
                flag=false;
            }


        }
        return jiajiaUser;
    }
    /**
     * 通过id查收入
     * @param transferBillsVo
     * @param realPrice
     * @param communityAgentsUserId
     * @param sysDictData
     */
    protected TransferBillsVo countAgentIncome(TransferBillsVo transferBillsVo , BigDecimal realPrice, Long communityAgentsUserId, SysDictData sysDictData,String type) {
        if (Optional.ofNullable(communityAgentsUserId).isPresent()) {
            JiajiaUser jiajiaUser = userService.selectJiajiaUserById(communityAgentsUserId);
            BigDecimal bigDecimal = realPrice.multiply(new BigDecimal(sysDictData.getDictValue())).setScale(0,RoundingMode.DOWN);
            //转账用户
            String openId="";
            if(Optional.ofNullable(jiajiaUser.getOpenId()).isPresent() && !jiajiaUser.getOpenId().equals("")){
                openId=jiajiaUser.getOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_MP);
            }else if(Optional.ofNullable(jiajiaUser.getGzhOpenId()).isPresent()&& !jiajiaUser.getGzhOpenId().equals("")){
                openId=jiajiaUser.getGzhOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_H5);
            }else{
                openId=jiajiaUser.getAppOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_APP);
            }
            transferBillsVo.setOpenid(openId);
            transferBillsVo.setTransferAmount(Integer.valueOf(bigDecimal.toString()));
            transferBillsVo.setTransferType(type);
            transferBillsVo.setUserId(communityAgentsUserId);

        }
        return transferBillsVo;
    }


    /**
     * 推广员收入
     * @param transferBillsVo
     * @param realPrice
     * @param sysDictData
     * @param jiajiaUser
     */
    private TransferBillsVo countPromoterIncome(TransferBillsVo transferBillsVo, BigDecimal realPrice, SysDictData sysDictData, JiajiaUser jiajiaUser,String type) {
        if(Optional.ofNullable(jiajiaUser).isPresent() &&Optional.ofNullable(jiajiaUser.getInviter()).isPresent() ){
            logger.info("type"+type+"realPrice:"+realPrice);
            logger.info("type"+type+"sysDictData.getDictValue():"+sysDictData.getDictValue());

            BigDecimal bigDecimal = realPrice.multiply(new BigDecimal(sysDictData.getDictValue())).setScale(0,RoundingMode.DOWN);
            logger.info("type"+type+"bigDecimal:"+bigDecimal);
            //转账用户
            String openId="";
            if(Optional.ofNullable(jiajiaUser.getOpenId()).isPresent() && !jiajiaUser.getOpenId().equals("")){
                openId=jiajiaUser.getOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_MP);
            }else if(Optional.ofNullable(jiajiaUser.getGzhOpenId()).isPresent()&& !jiajiaUser.getGzhOpenId().equals("")){
                openId=jiajiaUser.getGzhOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_H5);
            }else{
                openId=jiajiaUser.getAppOpenId();
                transferBillsVo.setPaymentChannels(TokenUtil.platforms_APP);
            }
            transferBillsVo.setOpenid(openId);
            transferBillsVo.setTransferAmount(Integer.valueOf(bigDecimal.toString()));
            transferBillsVo.setTransferType(type);
            transferBillsVo.setUserId(jiajiaUser.getId());

        }


        return transferBillsVo;
    }


}
